package cn.zmwh.manage.admin.modules.upms.service;

import cn.hutool.core.collection.CollUtil;
import cn.zmwh.manage.admin.modules.upms.mapper.SysRoleMenuMapper;
import cn.zmwh.manage.admin.modules.upms.pojo.entity.SysRoleMenu;
import cn.zmwh.manage.admin.modules.upms.pojo.request.RelevanceRequest;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 角色菜单关系 服务实现类
 * </p>
 *
 * @author dmzmwh
 * @since 2025-03-11
 */
@Service
public class SysRoleMenuService extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> {

    public void updateRelationByMenu(Long menuId, Set<Long> roleIds) {
        baseMapper.delete(Wrappers.<SysRoleMenu>lambdaQuery()
                .eq(SysRoleMenu::getMenuId, menuId));
        List<SysRoleMenu> sysRoleMenus = new ArrayList<>();
        roleIds.forEach(roleId -> {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(roleId);
            sysRoleMenu.setMenuId(menuId);
            sysRoleMenus.add(sysRoleMenu);
        });
        saveBatch(sysRoleMenus);
    }

    /**
     * 根据菜单删除角色关系
     *
     * @param menuId
     */
    public void delByMenu(Long menuId) {
        baseMapper.delete(Wrappers.<SysRoleMenu>lambdaQuery()
                .eq(SysRoleMenu::getMenuId, menuId));
    }

    public void relevance(RelevanceRequest request) {
        Long roleId = request.getRoleId();
        baseMapper.delete(Wrappers.<SysRoleMenu>lambdaQuery()
                .eq(SysRoleMenu::getRoleId, roleId));
        Set<Long> menuIds = request.getMenuIds();
        if (CollUtil.isEmpty(menuIds)) {
            return;
        }
        List<SysRoleMenu> sysRoleMenus = new ArrayList<>();
        menuIds.forEach(menuId -> {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(roleId);
            sysRoleMenu.setMenuId(menuId);
            sysRoleMenus.add(sysRoleMenu);
        });
        saveBatch(sysRoleMenus);
    }

    public void delByRoleId(Integer roleId) {
        baseMapper.delete(Wrappers.<SysRoleMenu>lambdaQuery()
                .eq(SysRoleMenu::getRoleId, roleId));
    }
}
